package com.cskaoyan.user.service.impl;

import com.alibaba.fastjson.JSON;
import com.cskaoyan.mall.commons.exception.ExceptionProcessorUtils;
import com.cskaoyan.mall.commons.exception.ValidateException;
import com.cskaoyan.mall.commons.util.jwt.AESUtil;
import com.cskaoyan.mall.commons.util.jwt.JwtTokenUtils;
import com.cskaoyan.user.constants.UserRetCode;
import com.cskaoyan.user.converter.UserConverterMapper;
import com.cskaoyan.user.dal.entitys.Member;
import com.cskaoyan.user.dal.entitys.Token;
import com.cskaoyan.user.dal.entitys.UserVerify;
import com.cskaoyan.user.dal.persistence.MemberMapper;
import com.cskaoyan.user.dal.persistence.UserVerifyMapper;
import com.cskaoyan.user.dto.UserLoginRequest;
import com.cskaoyan.user.dto.UserLoginResponse;
import com.cskaoyan.user.dto.UserRegisterRequest;
import com.cskaoyan.user.dto.UserRegisterResponse;

import com.cskaoyan.user.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;
import java.util.UUID;


@Service
@Transactional
public class IUserServiceImpl implements IUserService {
    @Autowired
    MemberMapper memberMapper;
    @Autowired
    UserConverterMapper userConverterMapper;
    @Autowired
    UserVerifyMapper userVerifyMapper;
    @Autowired
    JavaMailSender mailSender;
/*    @Value("${spring.mail.username}")
    private String sendMail;*/

    @Override
    public UserLoginResponse loginUser(UserLoginRequest request) {
        UserLoginResponse response = new UserLoginResponse();
        try {
            // 校验
            request.requestCheck();
            Example example = new Example(Member.class);
            example.createCriteria()
                    .andEqualTo("username", request.getUserName())
                    .andEqualTo("password", new AESUtil(request.getPassword()).encrypt());
            List<Member> members = memberMapper.selectByExample(example);

            if (members.size() > 0) {
                // 成功执行
                Member member = members.get(0);
                response = userConverterMapper.converter(member);
                response.setCode(UserRetCode.SUCCESS.getCode());
                response.setMsg(UserRetCode.SUCCESS.getMessage());
                if (member.getIsVerified().equals("N")) {
                    // 未激活
                    throw new ValidateException(UserRetCode.USER_ISVERFIED_ERROR.getCode(), UserRetCode.USER_ISVERFIED_ERROR.getMessage());
                }
                // 生成token
                Token token1 = new Token(member.getId(), member.getUsername());
                String string = JSON.toJSONString(token1);
                String token = JwtTokenUtils.builder().msg(string).build().creatJwtToken();
                response.setToken(token);
            } else {
                // 账号密码错误
                throw new ValidateException(UserRetCode.USERORPASSWORD_ERRROR.getCode(), UserRetCode.USERORPASSWORD_ERRROR.getMessage());
            }
        } catch (Exception e) {
            ExceptionProcessorUtils.wrapperHandlerException(response, e);
        }
        return response;
    }

    @Override
    public UserRegisterResponse register(UserRegisterRequest request) {
        UserRegisterResponse registerResponse = new UserRegisterResponse();
        try {
            request.requestCheck();
            // 判断用户名重复
            validUsername(request);

            Member member = userConverterMapper.converter2Member(request);
            member.setPassword(new AESUtil(request.getUserPwd()).encrypt());
            member.setCreated(new Date());
            member.setUpdated(new Date());
            int i = -1;
            try {
                i = memberMapper.insertSelective(member);
            } catch (Exception e) {
                e.printStackTrace();
            }

            // 判断用户表插入成功
            validInsertUser(i);

            // 用户激活表中插入
            UserVerify userVerify = new UserVerify();
            userVerify.setUsername(member.getUsername());
            String uuid = new AESUtil(member.getUsername() + UUID.randomUUID().toString()).encrypt().substring(0, 30);
            userVerify.setUuid(uuid);
            userVerify.setRegisterDate(new Date());
            userVerify.setIsExpire("N");
            userVerify.setIsVerify("Y");
            int rows = userVerifyMapper.insertSelective(userVerify);
            // 判断激活表插入成功
            validInsertUserVerify(rows);

            registerResponse.setCode(UserRetCode.SUCCESS.getCode());
            registerResponse.setMsg(UserRetCode.SUCCESS.getMessage());
            System.out.println("************************又向前************************");
            // todo 邮箱激活

            new Thread(new Runnable() {
                @Override
                public void run() {
                    sendMail(uuid, request);
                    System.out.println("************************邮箱后************************");
                }
            }).start();
        } catch (Exception e) {

            ExceptionProcessorUtils.wrapperHandlerException(registerResponse, e);
        }
        return registerResponse;
    }

    private void sendMail(String uuid, UserRegisterRequest request) {
//        BLJSEYGBVZFEDMWA
        SimpleMailMessage message = new SimpleMailMessage();
        message.setSubject("CSMALL激活");
        message.setFrom("wangjinnboo@163.com");
        message.setTo(request.getEmail());
        StringBuilder builder = new StringBuilder();
        builder.append("http://localhost:8099/user/verify?uid=").append(uuid).append("&username=").append(request.getUserName());
        message.setText(builder.toString());
        mailSender.send(message);
    }

    private void validInsertUser(int i) {
        if (i != 1) {
            throw new ValidateException(UserRetCode.USER_REGISTER_FAILED.getCode(), UserRetCode.USER_REGISTER_FAILED.getMessage());
        }
    }

    private void validInsertUserVerify(int i) {
        if (i != 1) {
            throw new ValidateException(UserRetCode.USER_REGISTER_VERIFY_FAILED.getCode(), UserRetCode.USER_REGISTER_VERIFY_FAILED.getMessage());
        }
    }

    private void validUsername(UserRegisterRequest request) {
        Example example = new Example(Member.class);
        example.createCriteria()
                .andEqualTo("username", request.getUserName());
        List<Member> members = memberMapper.selectByExample(example);
        if (members.size() > 0) {
            throw new ValidateException(UserRetCode.USERNAME_ALREADY_EXISTS.getCode(), UserRetCode.USERNAME_ALREADY_EXISTS.getMessage());
        }
    }
}
